<template>
  <div class="md-page-login">
    <div class="login-container">
      <div class="login-main">
        <ul class="tab-panel">
          <li :class="['tab-item', tabIndex === index ? 'tab-item-active' : '']" v-for="(item, index) in tabList" :key="index" @click="tabIndex = index">{{ item.name }}</li>
        </ul>
        <div class="login-form" v-show="tabIndex === 0">
          <!-- 登录 -->
          <el-form ref="formLogin" :model="form" :rules="rules">
            <el-form-item prop="email" label="Your Email Address:">
              <el-input v-model="form.email" placeholder="Please input email address" />
            </el-form-item>
            <el-form-item prop="userPwd" label="Password:">
              <el-input type="password" v-model="form.userPwd" class="w-300" placeholder="Please input password" show-password prefix-icon="el-icon-lock" />
            </el-form-item>
            <el-form-item>
              <div class="btn-box">
                <el-button type="primary" class="btn-submit" @click="handleLogin()">Login</el-button>
                <div class="foo">
                  Don't have an account yet? <a @click="handleShowRegister">Register</a>
                </div>
                <div class="foo" style="margin-bottom: -20px">
                  Can't remember the password? <a @click="flag = true">Forget</a>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="register-form" v-show="tabIndex === 1">
          <!-- 注册 -->
          <el-form class="form" ref="formRegister" :model="request" :rules="rules">
            <el-form-item prop="email" label="Your Email Address:">
              <el-input v-model="request.email" placeholder="Please input email address">
                <el-button slot="append" @click="sendEmail" :loading="btnLoading" title="send email code">Send</el-button>
              </el-input>
            </el-form-item>
            <el-form-item prop="code" label="Validate Code">
              <el-input v-model="request.code" maxlength="6" placeholder="Please input email code"></el-input>
            </el-form-item>
            <el-form-item prop="userPwd" label="Password">
              <el-input v-model="request.userPwd" type="password" placeholder="Password length: 8 to 16 characters!(A-Z+a-z+0-9)" />
            </el-form-item>
            <el-form-item prop="resPwd" label="Password Confirm">
              <el-input v-model="request.resPwd" type="password" placeholder="Confirm Password" />
            </el-form-item>
          </el-form>
          <el-button type="primary" class="btn-submit" @click="handleRegisterSubmit();">Register</el-button>
          <div class="foo">
            Already have an account? <a @click="handleShowLogin">Login</a>
          </div>
        </div>
      </div>
    </div>
    <md-forget-dialog :flag="flag" @close="flag = false"></md-forget-dialog>
  </div>
</template>

<script>
export default {
  name: 'MdPageRegisterComponent',
  layout: 'dynamic',
  data () {
    const validateEMail = (rule, value, callback) => {
      const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      if (value === '') {
        callback(new Error('This field is required!'))
      } else if (!reg.test(value)) {
        callback(new Error('Email invalid'))
      } else {
        callback()
      }
    }
    return {
      loginResponseEnum,
      registerResponseEnum,
      btnLoading: false,
      flag: false,
      tabIndex: 0, // 0 登录 1注册
      tabList: [
        { name: 'Login' },
        { name: 'Register' }
      ],
      // isRead: false,
      form: { // 登录form
        email: '',
        userPwd: ''
      },
      request, // 注册form
      rules: {
        email: [{ required: true, validator: validateEMail, trigger: 'blur' }],
        code: [{ required: true, message: 'Please input code', trigger: 'blur' }],
        userPwd: [
          { required: true, message: 'Password length: 8 to 16 characters!(A-Z+a-z+0-9)', trigger: 'blur' },
          { min: 8, max: 16, message: 'Password length: 8 to 16 characters!(A-Z+a-z+0-9)', trigger: 'blur' }
        ],
        resPwd: [
          { required: true, message: 'Password length: 8 to 16 characters!(A-Z+a-z+0-9)', trigger: 'blur' },
          { min: 8, max: 16, message: 'Password length: 8 to 16 characters!(A-Z+a-z+0-9)', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.request.userPwd !== value) {
                callback('Two passwords do not match!')
              }
              callback()
            }, trigger: 'blur'
          }
        ]
      },
      codeUuid: ''
    }
  },
  methods: {
    async handleLogin () {
      this.$refs.formLogin.validate(async valid => {
        if (!valid) {
          return
        }
        const params = {
          email: this.form.email,
          userPwd: this.form.userPwd,
          loginMode: '2' // 注册方式 1用户名 2邮箱 3手机号
        }

        const res = await this.$axios.post('web/user/login', params)
        if (res.code == 200 && res.data.token && res.data.user) {
          this.$message.success('login success!')
          this.$local.setItem('access_token', res.data.token)
          this.$local.setItem('user', res.data.user)
          this.$store.commit('changeLoginStatus', true)
          if (this.$route.query.turnBackPath) { // 如果携带路径过来，就跳转回去
            window.location.href = this.$route.query.turnBackPath
          } else {
            window.location.href = '/' // 登录后刷新页面
          }
        } else {
          this.$message.error(this.loginResponseEnum[res.data])
        }
      })
    },
    async sendEmail () {
      if (!this.request.email) {
        this.$message.error('please input email address!')
        return
      }
      this.btnLoading = true
      const params = {
        email: this.request.email
      }
      const res = await this.$axios.post('web/user/sendEmailVerificationCode', params)
      this.btnLoading = false
      if (res.code == 200) {
        this.$message.success('send success!')
        this.codeUuid = res.data?.uuid || ''
      }
    },
    handleRegisterSubmit () {
      this.$refs.formRegister.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = {
            email: this.request.email,
            code: this.request.code,
            codeUuid: this.codeUuid,
            userPwd: this.request.userPwd,
            registerMode: '2' // 注册方式 1用户名 2邮箱 3手机号
          }

          const res = await this.$axios.post('web/user/register', params)
          if (res.code == 200 && res.data.token && res.data.user) {
            this.$message.success('register success!')
            this.$local.setItem('access_token', res.data.token)
            this.$local.setItem('user', res.data.user)
            setTimeout(() => {
              this.$router.push('/experiencer/apply') //  注册完成之后跳转到体验师申请页
            }, 1000)
          } else {
            this.$message.error(this.registerResponseEnum[res.data])
          }
        } catch (error) {
          console.log(error)
        }
      })
    },
    handleShowLogin () {
      this.tabIndex = 0
      this.$refs.formLogin.resetFields()
    },
    handleShowRegister () {
      this.tabIndex = 1
      this.$refs.formRegister.resetFields()
    },
  }
}
const request = {
  email: '',
  code: '',
  userPwd: '',
  resPwd: '',
  registerMode: 2 // 注册方式 1用户名 2邮箱 3手机号
}

const loginResponseEnum = {
  'userName is empty': 'userName can not be empty',
  'email is empty': 'email can not be empty',
  'phone is empty': 'phone can not be empty',
  'not exist': 'Wrong password. Try again or click Forgot password to reset it.',
  'deactivated': 'user is deactivated'
}

const registerResponseEnum = {
  'code timeout': 'verification code timeout',
  'code incorrect': 'incorrect verification code',
  'userName is empty': 'userName can not be empty',
  'userName existed': 'userName already exists',
  'email is empty': 'email can not be empty',
  'email existed': 'email already exists',
  'phone is empty': 'phone can not be empty',
  'phone existed': 'phone already exists',
  'fail': 'Wrong password. Try again or click Forgot password to reset it.'
}
</script>

<style lang="scss" scoped>
.md-page-login {
  width: 100%;
  height: calc(100vh - 66px);
  // min-height: calc(100vh - 66px);
  box-sizing: border-box;

  .login-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    .login-main {
      margin: 20px 0;
      width: 500px;
      // height: 700px;
      background-color: #fff;
      border-radius: 3px;
      padding: 27px 37px;
      .tab-panel {
        width: 100%;
        border-bottom: 1px solid #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        .tab-item {
          width: 50%;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          color: #131313;
          cursor: pointer;
          &:first-child {
            border-right: 1px solid #f1f5f1;
            box-sizing: border-box;
          }
          &:hover {
            color: $md-primary-color;
          }
        }
        .tab-item-active {
          color: $md-primary-color;
        }
      }
    }
    .login-form,
    .register-form {
      // width: 464px;
      // height: 520px;

      .title {
        font-size: 22px;
        font-weight: bold;
        color: #1d2129;
        text-align: center;
      }

      ::v-deep .el-form {
        margin-top: 30px;
        .el-form-item:nth-child(2) {
          .el-form-item__content {
            .el-input {
              .el-input-group__append {
                background: transparent !important;
                span {
                  color: $md-primary-color;
                  font-size: 14px;
                  cursor: pointer;
                }
              }
            }
          }
        }
      }

      .desc {
        display: flex;
        align-items: center;
        margin-top: 13px;
        .el-checkbox {
          .el-checkbox__label {
            font-size: 14px;
            color: #86909c;

            span {
              a {
                text-decoration: none;
                color: $md-primary-color;
              }
            }
          }
        }

        a {
          flex: 1;
          text-align: right;
          text-decoration: none;
          font-size: 14px;
          color: #86909c;
        }
      }

      .btn-submit {
        width: 100%;
        font-size: 16px;
        margin-top: 30px;
      }

      .foo {
        font-size: 14px;
        color: #4e5969;
        margin-top: 12px;
        text-align: center;

        a {
          color: $md-primary-color;
          text-decoration: none;
          cursor: pointer;
        }
      }
    }
  }
}
</style>